<?php
/**
* @version $Id: admin.News.php 10002 2008-02-08 10:56:57Z willebil $
* @package Joomla
* @subpackage News
* @copyright Copyright (C) 2005 Open Source Matters. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL, see LICENSE.php
* Joomla! is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*/

// no direct access
defined( '_VALID_MOS' ) or die( 'Restricted access' );

require_once( $mainframe->getPath( 'admin_html' ) );

$sectionid 	= intval( mosGetParam( $_REQUEST, 'sectionid', 0 ) );

$cid 		= josGetArrayInts( 'cid' );

switch ($task) {
	case 'new':
		editNews( 0, $sectionid, $option );
		break;

	case 'edit':
		editNews( $id, $sectionid, $option );
		break;

	case 'editA':
		editNews( intval( $cid[0] ), '', $option );
		break;

	case 'save':
		saveNews( $sectionid, $task );
		break;
		
	case 'upload':
		uploadImage( $sectionid, $task );
		break;

	case 'delImage':
		delImage ( $sectionid, $task );
		break;

	case 'remove':
		removeNews( $cid, $sectionid, $option );
		break;

	case 'publish':
		changeNews( $cid, 1, $option );
		break;

	case 'unpublish':
		changeNews( $cid, 0, $option );
		break;

	case 'cancel':
		cancelNews();
		break;

	default:
		viewNews( $sectionid, $option );
		break;
}

/**
* Compiles a list of installed or defined modules
* @param database A database connector object
*/
function viewNews( $sectionid, $option ) {
	global $database, $mainframe, $mosConfig_list_limit;

	$catid 				= intval( $mainframe->getUserStateFromRequest( "catid{$option}{$sectionid}", 'catid', 0 ) );
	$filter_authorid 	= intval( $mainframe->getUserStateFromRequest( "filter_authorid{$option}{$sectionid}", 'filter_authorid', 0 ) );
	$filter_sectionid 	= intval( $mainframe->getUserStateFromRequest( "filter_sectionid{$option}{$sectionid}", 'filter_sectionid', 0 ) );
	$limit 				= intval( $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit ) );
	$limitstart 		= intval( $mainframe->getUserStateFromRequest( "view{$option}{$sectionid}limitstart", 'limitstart', 0 ) );
	$search 			= $mainframe->getUserStateFromRequest( "search{$option}{$sectionid}", 'search', '' );
	if (get_magic_quotes_gpc()) {
		$search			= stripslashes( $search );
	}
	$redirect 			= $sectionid;
	$filter 			= ''; //getting a undefined variable error

	if ( $sectionid == 0 ) {
		// used to show All News items
		$where = array(
		"c.state 	>= 0",
		"c.catid 	= cc.id",
		"cc.section = s.id",
		);
		$order = "\n ORDER BY s.title, c.catid, cc.ordering, cc.title, c.created DESC";
		$all = 1;
		//$filter = "\n , #__sections AS s WHERE s.id = c.section";

		if ($filter_sectionid > 0) {
			$filter = "\n WHERE cc.section = '" . (int) $filter_sectionid . "'";
		}
		$section->title = 'Tất cả tin khuyến mãi';
		$section->id = 0;
	} else {
		$where = array(
		"c.state 	>= 0",
		"c.catid 	= cc.id",
		"cc.section = s.id",
		"c.sectionid = " . (int) $sectionid
		);
		$order 		= "\n ORDER BY cc.ordering, cc.title, c.ordering";
		$all 		= NULL;
		$filter 	= "\n WHERE cc.section = '" . (int) $sectionid . "'";
		$section 	= new mosSection( $database );
		$section->load( (int)$sectionid );
	}

	// used by filter
	if ( $filter_sectionid > 0 ) {
		$where[] = "c.sectionid = " . (int) $filter_sectionid;
	}
	if ( $catid > 0 ) {
		$where[] = "c.catid = " . (int) $catid;
	}
	if ( $filter_authorid > 0 ) {
		$where[] = "c.created_by = " . (int) $filter_authorid;
	}

	if ( $search ) {
		$where[] = "LOWER( c.title ) LIKE '%" . $database->getEscaped( trim( strtolower( $search ) ) ) . "%'";
	}

	// get the total number of records
	$query = "SELECT COUNT(*)"
	. "\n FROM #__news AS c"
	. "\n LEFT JOIN #__categories AS cc ON cc.id = c.catid"
	. "\n LEFT JOIN #__sections AS s ON s.id = c.sectionid"
	. ( count( $where ) ? "\n WHERE " . implode( ' AND ', $where ) : "" )
	;
	$database->setQuery( $query );
	$total = $database->loadResult();
	require_once( $GLOBALS['mosConfig_absolute_path'] . '/administrator/includes/pageNavigation.php' );
	$pageNav = new mosPageNav( $total, $limitstart, $limit );

	$query = "SELECT c.*, s.title AS section_name, v.name AS author,cc.title AS name"
	. "\n FROM #__news AS c"
	. "\n LEFT JOIN #__categories AS cc ON cc.id = c.catid"
	. "\n LEFT JOIN #__sections AS s ON s.id = c.sectionid"
	. "\n LEFT JOIN #__users AS v ON v.id = c.created_by"
	. ( count( $where ) ? "\n WHERE " . implode( ' AND ', $where ) : '' )
	. $order
	;
	$database->setQuery( $query, $pageNav->limitstart, $pageNav->limit );
	$rows = $database->loadObjectList();

	if ($database->getErrorNum()) {
		echo $database->stderr();
		return false;
	}

	// get list of categories for dropdown filter
	$query = "SELECT cc.id AS value, cc.title AS text, section"
	. "\n FROM #__categories AS cc"
	. "\n INNER JOIN #__sections AS s ON s.id = cc.section "
	. $filter
	. "\n ORDER BY s.ordering, cc.ordering"
	;
	$lists['catid'] 	= filterCategory( $query, $catid );

	// get list of sections for dropdown filter
	$javascript = 'onchange="document.adminForm.submit();"';
	$lists['sectionid']	= mosAdminMenus::SelectSection( 'filter_sectionid', $filter_sectionid, $javascript );

	// get list of Authors for dropdown filter
	$query = "SELECT c.created_by, u.name"
	. "\n FROM #__news AS c"
	. "\n INNER JOIN #__sections AS s ON s.id = c.sectionid"
	. "\n LEFT JOIN #__users AS u ON u.id = c.created_by"
	. "\n WHERE c.state != -1"
	. "\n AND c.state != -2"
	. "\n GROUP BY u.name"
	. "\n ORDER BY u.name"
	;
	$authors[] = mosHTML::makeOption( '0', _SEL_AUTHOR, 'created_by', 'name' );
	$database->setQuery( $query );
	$authors = array_merge( $authors, $database->loadObjectList() );
	$lists['authorid']	= mosHTML::selectList( $authors, 'filter_authorid', 'class="inputbox" size="1" onchange="document.adminForm.submit( );"', 'created_by', 'name', $filter_authorid );

	HTML_News::showNews( $rows, $section, $lists, $search, $pageNav, $all, $redirect );
}

/**
* Compiles information to add or edit the record
* @param database A database connector object
* @param integer The unique id of the record to edit (0 if new)
* @param integer The id of the News section
*/
function editNews( $uid=0, $sectionid=0, $option ) {
	global $database, $my, $mainframe;
	global $mosConfig_absolute_path, $mosConfig_live_site, $mosConfig_offset, $mosConfig_dbprefix;
	
	$redirect = strval( mosGetParam( $_POST, 'redirect', '' ) );
	$nullDate = $database->getNullDate();
	
	if ( !$redirect ) {
		$redirect = $sectionid;
	}

	// load the row from the db table
	$row = new mosNews( $database );
	$row->load( (int)$uid );

	if ($uid) {
		$sectionid = $row->sectionid;
		if ($row->state < 0) {
			mosRedirect( 'index2.php?option=com_news&sectionid='. $row->sectionid, 'You cannot edit an archived item' );
		}
	}

	$selected_folders = NULL;
	if ($uid) {
		$row->checkout( $my->id );
 		$row->created 		= mosFormatDate( $row->created, _CURRENT_SERVER_TIME_FORMAT );

	} else {
		if ( !$sectionid && @$_POST['filter_sectionid'] ) {
			$sectionid = $_POST['filter_sectionid'];
		}
		if ( @$_POST['catid'] ) {
			$row->catid 	= (int)$_POST['catid'];
			$category = new mosCategory( $database );
			$category->load( (int)$_POST['catid'] );
			$sectionid = $category->section;
		} else {
			$row->catid 	= 0;
		}

		$row->sectionid 	= $sectionid;
		$row->state 		= 1;
		$menus = array();
	}

	$javascript = "onchange=\"changeDynaList( 'catid', sectioncategories, document.adminForm.sectionid.options[document.adminForm.sectionid.selectedIndex].value, 0, 0);\"";

	$query = "SELECT s.id, s.title"
	. "\n FROM #__sections AS s"
	. "\n ORDER BY s.ordering";
	$database->setQuery( $query );
	if ( $sectionid == 0 ) {
		$sections[] = mosHTML::makeOption( '-1', 'Select Section', 'id', 'title' );
		$sections = array_merge( $sections, $database->loadObjectList() );
		$lists['sectionid'] = mosHTML::selectList( $sections, 'sectionid', 'class="inputbox" size="1" '. $javascript, 'id', 'title' );
	} else {
		$sections = $database->loadObjectList();
		$lists['sectionid'] = mosHTML::selectList( $sections, 'sectionid', 'class="inputbox" size="1" '. $javascript, 'id', 'title', intval( $row->sectionid ) );
	}

	$section = '';
	foreach($sections as $section) {
		$section_list[] = $section->id;
		// get the type name - which is a special category
		if ($row->sectionid){
			if ( $section->id == $row->sectionid ) {
				$section = $section->title;
				$sectionid		= $section->id;
			}
		} else {
			if ( $section->id == $sectionid ) {
				$section = $section->title;
				$sectionid		= $section->id;
			}
		}
	}

	$sectioncategories 			= array();
	$sectioncategories[-1] 		= array();
	$sectioncategories[-1][] 	= mosHTML::makeOption( '-1', 'Select Category', 'id', 'name' );
	mosArrayToInts( $section_list );
	$section_list 				= 'section=' . implode( ' OR section=', $section_list );

	$query = "SELECT id, name, section"
	. "\n FROM #__categories"
	. "\n WHERE ( $section_list )"
	. "\n ORDER BY ordering"
	;
	$database->setQuery( $query );
	$cat_list = $database->loadObjectList();
	foreach($sections as $section) {
		$sectioncategories[$section->id] = array();
		$rows2 = array();
		foreach($cat_list as $cat) {
			if ($cat->section == $section->id) {
				$rows2[] = $cat;
			}
		}
		foreach($rows2 as $row2) {
			$sectioncategories[$section->id][] = mosHTML::makeOption( $row2->id, $row2->name, 'id', 'name' );
		}
	}

 	// get list of categories
  	if ( !$row->catid && !$row->sectionid ) {
 		$categories[] 		= mosHTML::makeOption( '-1', 'Select Category', 'id', 'name' );
 		$lists['catid'] 	= mosHTML::selectList( $categories, 'catid', 'class="inputbox" size="1"', 'id', 'name' );
  	} else {
		$categoriesA = array();
		if ( $sectionid == 0 ) {
			//$where = "\n WHERE section NOT LIKE '%com_%'";
			foreach($cat_list as $cat) {
				$categoriesA[] = $cat;
			}
		} else {
			//$where = "\n WHERE section = '$sectionid'";
			foreach($cat_list as $cat) {
				if ($cat->section == $sectionid) {
					$categoriesA[] = $cat;
				}
			}
		}
		$categories[] 		= mosHTML::makeOption( '-1', 'Select Category', 'id', 'name' );
		$categories 		= array_merge( $categories, $categoriesA );
 		$lists['catid'] 	= mosHTML::selectList( $categories, 'catid', 'class="inputbox" size="1"', 'id', 'name', intval( $row->catid ) );
  	}

	// pull param column from category info
	$query = "SELECT params"
	. "\n FROM #__categories"
	. "\n WHERE id = " . (int) $row->catid
	;
	$database->setQuery( $query );
	$categoryParam = $database->loadResult();

	$paramsCat = new mosParameters( $categoryParam, $mainframe->getPath( 'com_xml', 'com_categories' ), 'component' );
	$selected_folders = $paramsCat->get( 'imagefolders', '' );

	if ( !$selected_folders ) {
		$selected_folders = '*2*';
	}

	// check if images utilizes settings from section
	if ( strpos( $selected_folders, '*2*' ) !== false ) {
		unset( $selected_folders );
		// load param column from section info
		$query = "SELECT params"
		. "\n FROM #__sections"
		. "\n WHERE id = " . (int) $row->sectionid
		;
		$database->setQuery( $query );
		$sectionParam = $database->loadResult();

		$paramsSec = new mosParameters( $sectionParam, $mainframe->getPath( 'com_xml', 'com_sections' ), 'component' );
		$selected_folders = $paramsSec->get( 'imagefolders', '' );
	}

	if ( trim( $selected_folders ) ) {
		$temps = explode( ',', $selected_folders );
		foreach( $temps as $temp ) {
			$temp 		= ampReplace( $temp);
			$folders[] 	= mosHTML::makeOption( $temp, $temp );
		}
	} else {
		$folders[] = mosHTML::makeOption( '*1*' );
	}

	// build list of users
	$active = ( intval( $row->created_by ) ? intval( $row->created_by ) : $my->id );
	$lists['created_by'] 		= mosAdminMenus::UserSelect( 'created_by', $active );
	
	//get content
	$sql = "SELECT cd.title AS title, cd.id AS id, s.title AS titlecat"
		."\n FROM ".$mosConfig_dbprefix."content AS cd, ".$mosConfig_dbprefix."sections AS s"
		."\n WHERE cd.sectionid=s.id AND cd.state=1 AND s.published=1"
		."\n ORDER BY s.id, cd.sectionid DESC"
		;
	$database->setQuery($sql);
	$lsContentNews = $database->loadObjectList();

	// get params definitions
	$params = new mosParameters( $row->attribs, $mainframe->getPath( 'com_xml', 'com_news' ), 'component' );
	
	//get content_id
	$sql = "SELECT content_id FROM ".$mosConfig_dbprefix."news_content WHERE news_id=".$row->id;
	$database->setQuery($sql);
	$lsIDContent = $database->loadObjectList();
	
	HTML_News::editNews( $row, $section, $sectionid, $lists, $sectioncategories, $params, $option, $redirect, $lsContentNews, $lsIDContent );
}

/**
* Saves the News item an edit form submit
* @param database A database connector object
*/
function saveNews( $sectionid, $task ) {
	global $database, $my, $mainframe, $mosConfig_offset, $mosConfig_absolute_path, $mosConfig_dbprefix;
	josSpoofCheck();
	
	$menu 		= strval( mosGetParam( $_POST, 'menu', 'mainmenu' ) );
	$menuid		= intval( mosGetParam( $_POST, 'menuid', 0 ) );
	//Get the new coordinates to crop the image.
	$x1 		= intval( mosGetParam( $_REQUEST, 'x1', 0 ) );
	$y1 		= intval( mosGetParam( $_REQUEST, 'y1', 0 ) );
	$x2 		= intval( mosGetParam( $_REQUEST, 'x2', 0 ) );
	$y2 		= intval( mosGetParam( $_REQUEST, 'y2', 0 ) );
	$w	 		= intval( mosGetParam( $_REQUEST, 'w', 0 ) );
	$h	 		= intval( mosGetParam( $_REQUEST, 'h', 0 ) );
	
	$content_id=$_POST['content_id'];

	$nullDate 	= $database->getNullDate();
	
	$row = new mosNews( $database );
	if (!$row->bind( $_POST )) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}

	// sanitise id field
	$row->id = (int) $row->id;
	$row->created_by 	= $row->created_by ? $row->created_by : $my->id;
	if ($row->created && strlen(trim( $row->created )) <= 10) {
		$row->created 	.= ' 00:00:00';
	}
	$row->created 		= $row->created ? mosFormatDate( $row->created, '%Y-%m-%d %H:%M:%S', -$mosConfig_offset ) : date( 'Y-m-d H:i:s' );
	$row->state 		= intval( mosGetParam( $_REQUEST, 'state', 0 ) );
	
	$params = mosGetParam( $_POST, 'params', '' );
	if (is_array( $params )) {
		$txt = array();
		foreach ( $params as $k=>$v) {
			if (get_magic_quotes_gpc()) {
				$v = stripslashes( $v );
			}
			$txt[] = "$k=$v";
		}
		$row->attribs = implode( "\n", $txt );
	}

	// code cleaner for xhtml transitional compliance
	$row->introtext = str_replace( '<br>', '<br />', $row->introtext );
	$row->fulltext 	= str_replace( '<br>', '<br />', $row->fulltext );

 	// remove <br /> take being automatically added to empty fulltext
 	$length	= strlen( $row->fulltext ) < 9;
 	$search = strstr( $row->fulltext, '<br />');
 	if ( $length && $search ) {
 		$row->fulltext = NULL;
 	}

	$row->title 		= ampReplace( $row->title );
	$title_alias 		= mosGetParam($_REQUEST, 'title', '');
	$title_seo			= RemoveSign($title_alias);
	$title_seo_en		= str_replace(" ", "-", $title_seo);
	$title_seo_en		= preg_replace('/[^a-z0-9]+/i','-',$title_seo_en);
	
	$row->title_alias 	= $title_seo_en;
 	if (!$row->check()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}			
	
	//upload and crop image
	$uploaddir = $mosConfig_absolute_path."/uploads/news";
	$upload_path = $uploaddir;
	
	$large_image_name = $title_seo_en."_large_pic.jpg"; 		// New name of the large image
	$medium_image_name = $title_seo_en."_medium_pic.jpg"; 		// New name of the medium image
	$thumb_image_name = $title_seo_en."_thumbnail_pic.jpg"; 	// New name of the thumbnail image
	$max_file = "1148576"; 										// Approx 1MB
	$max_width = "500";											// Max width allowed for the large image
	$medium_width = "160";										// Width of medium image
	$medium_height = "160";
	$thumb_width = "80";										// Width of thumbnail image
	$thumb_height = "60";

	//Image Locations
	$large_image_location 	= $upload_path."/large/".$large_image_name;
	$medium_image_location 	= $upload_path."/medium/".$medium_image_name;
	$thumb_image_location 	= $upload_path."/thumbnail/".$thumb_image_name;
	
	//Get the file information
	$userfile_name = $_FILES['img']['name'];
	$userfile_tmp = $_FILES['img']['tmp_name'];
	$userfile_size = $_FILES['img']['size'];
	$filename = basename($_FILES['img']['name']);
	$file_ext = substr($filename, strrpos($filename, '.') + 1);
	
	//Only process if the file is a JPG and below the allowed limit
	if((!empty($_FILES["img"])) && ($_FILES['img']['error'] == 0)) {
		if (($file_ext!="jpg") && ($userfile_size > $max_file)) {
			$error= "CHỈ hình ảnh jpeg dưới 1MB được chấp nhận cho tải lên";
		}
	}else{
		$error= "Chọn một hình ảnh jpeg để tải lên";
	}
	
	if($row->id==0){
		if (copy ( $mosConfig_absolute_path."/uploads/temp/temp_pic.jpg", $uploaddir."/large/".$large_image_name)){
			@unlink($mosConfig_absolute_path."/uploads/temp/temp_pic.jpg");
			$row->largeImage = $large_image_name;
		}
		//Scale the image to the medium_width set above
		$scale = $medium_width/$w;
		$cropped = resizeThumbnailImage($medium_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
		$row->mediumImage = $medium_image_name;
		if (copy ( $medium_image_location, $thumb_image_location)){
			$row->thumbnailImage = $thumb_image_name;
			Resize_File($row->thumbnailImage, $upload_path."/thumbnail/", $thumb_width, $thumb_height);
		}
		//Add khuyen mai
		if ($content_id){
			$sql = "SELECT max(id) AS maxid FROM ".$mosConfig_dbprefix."news";
			$database->setQuery($sql);
			$database->loadObject($MAX);
			$maxid = $MAX->maxid+1;
			foreach ($content_id as $conent){
		 		mysql_query("INSERT INTO ".$mosConfig_dbprefix."news_content(news_id,content_id) VALUES(".$maxid.",".$conent.")");
			}
		}
	}else{
		if (copy ( $mosConfig_absolute_path."/uploads/temp/temp_pic.jpg", $uploaddir."/large/".$large_image_name)){
			@unlink($mosConfig_absolute_path."/uploads/temp/temp_pic.jpg");
			$row->largeImage = $large_image_name;
		}
		//Scale the image to the medium_width set above
		$scale = $medium_width/$w;
		$cropped = resizeThumbnailImage($medium_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
		$row->mediumImage = $medium_image_name;
		if (copy ( $medium_image_location, $thumb_image_location)){
			$row->thumbnailImage = $thumb_image_name;
			Resize_File($row->thumbnailImage, $upload_path."/thumbnail/", $thumb_width, $thumb_height);
		}
		//Add or change khuyen mai
		if ($content_id){
			mysql_query("DELETE FROM ".$mosConfig_dbprefix."news_content WHERE news_id=".$row->id);
			foreach ($content_id as $conent){
		 		mysql_query("INSERT INTO ".$mosConfig_dbprefix."news_content(news_id,content_id) VALUES(".$row->id.",".$conent.")");
			}
		}
	}
	
	if (!$row->store()) {
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}

	// clean any existing cache files
	mosCache::cleanCache( 'com_news' );

	$redirect = mosGetParam( $_POST, 'redirect', $sectionid );
	switch ( $task ) {
		case 'save':
		default:
			$msg = 'Successfully Saved Item: '. $row->title;
			mosRedirect( 'index2.php?option=com_news&sectionid='. $redirect, $msg );

			break;
	}
}

function uploadImage( $sectionid, $task ){
	global $database, $my, $mainframe, $mosConfig_offset, $mosConfig_absolute_path;
	
	$id		= intval(mosGetParam($_REQUEST, 'id', 0));
	
	$userfile_name = $_FILES['image']['name'];
	$userfile_tmp = $_FILES['image']['tmp_name'];
	$userfile_size = $_FILES['image']['size'];
	$filename = basename($_FILES['image']['name']);
	$file_ext = substr($filename, strrpos($filename, '.') + 1);
	
	//Only process if the file is a JPG and below the allowed limit
	if((!empty($_FILES["image"])) && ($_FILES['image']['error'] == 0)) {
		if (($file_ext!="jpg") && ($userfile_size > $max_file)) {
			$msg= "Chỉ ảnh jpeg dưới 1MB mới được chấp nhận cho tải lên !";
		}
	}else{
		$msg= "Select a jpeg image for upload";
	}
	
	$large_image_name = 'temp_pic';
	$uploaddir = $mosConfig_absolute_path."/uploads/temp/";
	
	if (strlen($msg)==0){
		$upload = $uploaddir . basename(get_new_file_name($_FILES['image']['name'],$large_image_name.""));		  					
		if (move_uploaded_file($_FILES['image']['tmp_name'], $upload)) {
			$msg = 'Upload ảnh thành công !';					
		}else{
			$msg = 'Upload ảnh lỗi, hãy thử lại !';
		}
	}
	
	//$msg = 'Uploads Successfully !';
	mosRedirect( 'index2.php?option=com_news&sectionid='. $redirect .'&task=edit&hidemainmenu=1&id='.$id, $msg );
}

function delImage( $sectionid, $task ){
	global $database, $my, $mainframe, $mosConfig_offset, $mosConfig_absolute_path, $mosConfig_dbprefix;
	$path = $mosConfig_absolute_path."/uploads/News";
	
	$id		= intval(mosGetParam($_REQUEST, 'id', 0));
	$sql = "SELECT largeImage,mediumImage,thumbnailImage FROM #__news WHERE id=".$id;
	$database->setQuery($sql);
	$database->loadObject($row);
	
	if ($row->largeImage!=''){
		$update = "UPDATE ".$mosConfig_dbprefix."News"
				."\n SET largeImage='',"
				."\n mediumImage='',"
				."\n thumbnailImage=''"
				."\n WHERE id=".$id
				;
		if (mysql_query($update)){
			@unlink($path."/large/".$row->largeImage);
			@unlink($path."/medium/".$row->mediumImage);
			@unlink($path."/thumbnail/".$row->thumbnailImage);
			$msg = 'Ảnh đã được xóa khỏi sản phẩm !';
		}else{
			$msg = 'Có lỗi xảy ra trong quá trình xóa ảnh sản phẩm, vui lòng thử lại !';
		}		
	}
	mosRedirect( 'index2.php?option=com_news&sectionid='. $redirect .'&task=edit&hidemainmenu=1&id='.$id, $msg );
}

function removeNews( &$cid, $sectionid, $option ) {
	global $database, $mosConfig_absolute_path;
	$path = $mosConfig_absolute_path."/uploads/News";

	josSpoofCheck();

	$total = count( $cid );
	if ( $total < 1) {
		echo "<script> alert('Select an item to delete'); window.history.go(-1);</script>\n";
		exit;
	}

	$state = '-2';
	$ordering = '0';
	//seperate Newsids
	mosArrayToInts( $cid );
	$cids = 'id=' . implode( ' OR id=', $cid );
	
	$sql = "SELECT * FROM #__news WHERE ( $cids )";
	$database->setQuery($sql);
	$lsImage = $database->loadObjectList();
	for ($i=0; $i<count($lsImage); $i++){
		echo $lsImage[$i]->largeImage;
		if(file_exists($path."/large/".$lsImage[$i]->largeImage)) {
		   @unlink($path."/large/".$lsImage[$i]->largeImage);
		}
		if(file_exists($path."/medium/".$lsImage[$i]->mediumImage)) {
		   @unlink($path."/medium/".$lsImage[$i]->mediumImage);
		}
		if(file_exists($path."/thumbnail/".$lsImage[$i]->thumbnailImage)) {
		   @unlink($path."/thumbnail/".$lsImage[$i]->thumbnailImage);
		}
	}
	
	$query = "UPDATE #__news"
	. "\n SET state = " . (int) $state . ", ordering = " . (int) $ordering
	. "\n WHERE ( $cids )"
	;
	$database->setQuery( $query );
	if ( !$database->query() ) {
		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		exit();
	}

	// clean any existing cache files
	mosCache::cleanCache( 'com_news' );

	$msg 	= $total ." Item(s) sent to the Trash";
	$return = strval( mosGetParam( $_POST, 'returntask', '' ) );
	mosRedirect( 'index2.php?option='. $option .'&task='. $return .'&sectionid='. $sectionid, $msg );
}

function changeNews( $cid=null, $state=0, $option ) {
	global $database, $my, $task;

	josSpoofCheck();

	if (count( $cid ) < 1) {
		$action = $state == 1 ? 'publish' : ($state == -1 ? 'archive' : 'unpublish');
		echo "<script> alert('Select an item to $action'); window.history.go(-1);</script>\n";
		exit;
	}

	mosArrayToInts( $cid );
	$total = count ( $cid );
	$cids = 'id=' . implode( ' OR id=', $cid );

	$query = "UPDATE #__news"
	. "\n SET state = " . (int) $state
	. "\n WHERE ( $cids )"
	;
	$database->setQuery( $query );
	if (!$database->query()) {
		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		exit();
	}

	if (count( $cid ) == 1) {
		$row = new mosNews( $database );
		$row->checkin( $cid[0] );
	}

	// clean any existing cache files
	mosCache::cleanCache( 'com_news' );

	switch ( $state ) {
		case -1:
			$msg = $total .' Item(s) successfully Archived';
			break;

		case 1:
			$msg = $total .' Item(s) successfully Published';
			break;

		case 0:
		default:
			if ( $task == 'unarchive' ) {
				$msg = $total .' Item(s) successfully Unarchived';
			} else {
				$msg = $total .' Item(s) successfully Unpublished';
			}
			break;
	}

	$redirect 	= mosGetParam( $_POST, 'redirect', $row->sectionid );
	$rtask 		= strval( mosGetParam( $_POST, 'returntask', '' ) );
	if ( $rtask ) {
		$rtask = '&task='. $rtask;
	} else {
		$rtask = '';
	}

	mosRedirect( 'index2.php?option='. $option . $rtask .'&sectionid='. $redirect .'&mosmsg='. $msg );
}

/**
* Cancels an edit operation
*/
function cancelNews( ) {
	global $database;

	josSpoofCheck();

	$row = new mosNews( $database );
	$row->bind( $_POST );
	$row->checkin();

	$redirect = mosGetParam( $_POST, 'redirect', 0 );
	mosRedirect( 'index2.php?option=com_news&sectionid='. $redirect );
}

function filterCategory( $query, $active=NULL ) {
	global $database;

	$categories[] = mosHTML::makeOption( '0', _SEL_CATEGORY );
	$database->setQuery( $query );
	$categories = array_merge( $categories, $database->loadObjectList() );

	$category = mosHTML::selectList( $categories, 'catid', 'class="inputbox" size="1" onchange="document.adminForm.submit( );"', 'value', 'text', $active );

	return $category;
}
?>
